<template>
  <div class="order-management">
    <!-- 操作栏 -->
    <div class="operation-bar">
      <el-input
        v-model="searchText"
        placeholder="搜索订单编号/客户姓名/餐厅"
        style="width: 360px"
        clearable
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>新增订单
      </el-button>
    </div>

    <!-- 数据表格 -->
    <el-table 
      :data="filteredOrders" 
      border 
      style="width: 100%"
      header-row-class-name="table-header"
      stripe
      highlight-current-row
    >
      <el-table-column prop="orderId" label="订单编号" width="180" sortable align="center" />
      <el-table-column prop="customer" label="客户姓名" width="120" align="center"/>
      <el-table-column prop="restaurant" label="餐厅名称" width="180" align="center">
        <template #default="{ row }">
          <el-tag effect="plain" :type="restaurantTagType[row.restaurant]">
            {{ row.restaurant }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="phone" label="联系方式" width="180" align="center"/>
      <el-table-column prop="amount" label="订单金额" width="120" align="center">
        <template #default="{ row }">
          <span style="color: #e74c3c;">¥{{ row.amount }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="paymentStatus" label="支付状态" width="140" align="center">
        <template #default="{ row }">
          <el-tag :type="paymentTagType[row.paymentStatus]" effect="light">
            {{ paymentOptions.find(s => s.value === row.paymentStatus)?.label }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="deliveryStatus" label="配送状态" width="140" align="center">
        <template #default="{ row }">
          <el-tag :type="deliveryTagType[row.deliveryStatus]" effect="light">
            {{ deliveryOptions.find(s => s.value === row.deliveryStatus)?.label }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="address" label="配送地址" width="250" align="center"/>
      <el-table-column label="操作" width="190" fixed="right" align="center">
        <template #default="{ row }">
          <el-button size="small" type="primary" plain @click="handleEdit(row)">编辑</el-button>
          <el-button
            size="small"
            type="danger"
            plain
            @click="handleDelete(row.orderId)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEditMode ? '编辑订单信息' : '新增订单信息'"
      width="680"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
        label-position="left"
      >
        <el-form-item label="订单编号" prop="orderId">
          <el-input 
            v-model="formData.orderId" 
            :disabled="isEditMode"
            placeholder="OD开头+8位日期+3位序列"
          />
        </el-form-item>
        <el-form-item label="客户姓名" prop="customer">
          <el-input v-model="formData.customer" placeholder="请输入客户姓名"/>
        </el-form-item>
        <el-form-item label="餐厅名称" prop="restaurant">
          <el-select 
            v-model="formData.restaurant"
            placeholder="请选择餐厅"
            style="width: 100%"
          >
            <el-option
              v-for="item in restaurants"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="联系方式" prop="phone">
          <el-input 
            v-model="formData.phone"
            placeholder="请输入联系电话"
          />
        </el-form-item>
        <el-form-item label="订单金额" prop="amount">
          <el-input-number
            v-model="formData.amount"
            :min="0"
            :precision="2"
            controls-position="right"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="支付状态" prop="paymentStatus">
          <el-select 
            v-model="formData.paymentStatus"
            placeholder="请选择支付状态"
            style="width: 100%"
          >
            <el-option
              v-for="item in paymentOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="配送状态" prop="deliveryStatus">
          <el-select 
            v-model="formData.deliveryStatus"
            placeholder="请选择配送状态"
            style="width: 100%"
          >
            <el-option
              v-for="item in deliveryOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="配送地址" prop="address">
          <el-input 
            v-model="formData.address"
            placeholder="请输入详细配送地址"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, reactive, watch, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus } from '@element-plus/icons-vue'

// SessionStorage 操作工具
const STORAGE_KEY = 'order_management_state'
const saveToStorage = (state) => {
  sessionStorage.setItem(STORAGE_KEY, JSON.stringify(state))
}
const loadFromStorage = () => {
  const data = sessionStorage.getItem(STORAGE_KEY)
  return data ? JSON.parse(data) : {}
}

// 餐厅配置
const restaurants = [
  '海底捞火锅',
  '必胜客披萨',
  '星巴克咖啡',
  '肯德基快餐',
  '绿茶餐厅',
  '西贝莜面村'
]

// 标签样式映射
const restaurantTagType = {
  '海底捞火锅': 'danger',
  '必胜客披萨': 'warning',
  '星巴克咖啡': 'info',
  '肯德基快餐': 'primary',
  '绿茶餐厅': 'success',
  '西贝莜面村': ''
}

// 支付状态选项
const paymentOptions = [
  { value: 'unpaid', label: '待支付' },
  { value: 'paid', label: '已支付' },
  { value: 'refunded', label: '已退款' }
]

const paymentTagType = {
  'unpaid': 'warning',
  'paid': 'success',
  'refunded': 'danger'
}

// 配送状态选项
const deliveryOptions = [
  { value: 'pending', label: '待接单' },
  { value: 'preparing', label: '备餐中' },
  { value: 'delivering', label: '配送中' },
  { value: 'completed', label: '已完成' }
]

const deliveryTagType = {
  'pending': 'info',
  'preparing': 'primary',
  'delivering': 'warning',
  'completed': 'success'
}

// 从 SessionStorage 加载初始状态
const storedState = loadFromStorage()

// 初始订单数据（优先从 SessionStorage 恢复）
const orders = ref(storedState.orders || [
  {
    orderId: 'OD20240519001',
    customer: '张晓明',
    restaurant: '海底捞火锅',
    phone: '13800138001',
    amount: 268.0,
    paymentStatus: 'paid',
    deliveryStatus: 'completed',
    address: '北京市朝阳区建国路123号'
  },
  {
    orderId: 'OD20240519002',
    customer: '李芳芳',
    restaurant: '必胜客披萨',
    phone: '13800138002',
    amount: 158.5,
    paymentStatus: 'unpaid',
    deliveryStatus: 'pending',
    address: '上海市浦东新区世纪大道456号'
  },
  {
    orderId: 'OD20240519003',
    customer: '王伟',
    restaurant: '星巴克咖啡',
    phone: '13800138003',
    amount: 45.0,
    paymentStatus: 'paid',
    deliveryStatus: 'delivering',
    address: '广州市天河区珠江新城789号'
  },
  {
    orderId: 'OD20240519004',
    customer: '陈莉莉',
    restaurant: '肯德基快餐',
    phone: '13800138004',
    amount: 78.0,
    paymentStatus: 'paid',
    deliveryStatus: 'preparing',
    address: '深圳市南山区科技园101号'
  },
  {
    orderId: 'OD20240519005',
    customer: '赵建国',
    restaurant: '绿茶餐厅',
    phone: '13800138005',
    amount: 320.0,
    paymentStatus: 'refunded',
    deliveryStatus: 'completed',
    address: '杭州市西湖区文三路222号'
  },
  {
    orderId: 'OD20240519006',
    customer: '孙婷婷',
    restaurant: '西贝莜面村',
    phone: '13800138006',
    amount: 195.0,
    paymentStatus: 'paid',
    deliveryStatus: 'delivering',
    address: '南京市鼓楼区中山路333号'
  },
  {
    orderId: 'OD20240519007',
    customer: '周强',
    restaurant: '海底捞火锅',
    phone: '13800138007',
    amount: 420.0,
    paymentStatus: 'paid',
    deliveryStatus: 'preparing',
    address: '成都市武侯区天府大道444号'
  },
  {
    orderId: 'OD20240519008',
    customer: '吴敏',
    restaurant: '必胜客披萨',
    phone: '13800138008',
    amount: 128.0,
    paymentStatus: 'unpaid',
    deliveryStatus: 'pending',
    address: '武汉市江汉区建设路555号'
  },
  {
    orderId: 'OD20240519009',
    customer: '郑浩然',
    restaurant: '星巴克咖啡',
    phone: '13800138009',
    amount: 65.0,
    paymentStatus: 'paid',
    deliveryStatus: 'completed',
    address: '西安市雁塔区科技路666号'
  },
  {
    orderId: 'OD20240519010',
    customer: '徐丽华',
    restaurant: '肯德基快餐',
    phone: '13800138010',
    amount: 89.0,
    paymentStatus: 'paid',
    deliveryStatus: 'delivering',
    address: '重庆市渝中区解放路777号'
  }
])

// 搜索功能（从 SessionStorage 恢复搜索词）
const searchText = ref(storedState.searchText || '')
const filteredOrders = computed(() => {
  return orders.value.filter(order => {
    return Object.values(order).some(value => 
      String(value).toLowerCase().includes(searchText.value.toLowerCase())
    )
  })
})

// 对话框相关状态（从 SessionStorage 恢复）
const dialogVisible = ref(storedState.dialogVisible || false)
const isEditMode = ref(storedState.isEditMode || false)
const formRef = ref(null)
const formData = reactive(storedState.formData || {
  orderId: '',
  customer: '',
  restaurant: '',
  phone: '',
  amount: 0,
  paymentStatus: 'unpaid',
  deliveryStatus: 'pending',
  address: ''
})

// 表单验证规则
const formRules = {
  orderId: [
    { required: true, message: '请输入订单编号', trigger: 'blur' },
    { pattern: /^OD\d{8}\d{3}$/, message: '格式要求：OD+8位日期+3位序列', trigger: 'blur' }
  ],
  customer: [
    { required: true, message: '请输入客户姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在2到20个字符', trigger: 'blur' }
  ],
  restaurant: { required: true, message: '请选择餐厅', trigger: 'change' },
  phone: [
    { required: true, message: '请输入联系方式', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入有效手机号', trigger: 'blur' }
  ],
  amount: [
    { required: true, message: '请输入订单金额', trigger: 'blur' },
    { type: 'number', min: 0, max: 9999, message: '金额范围0-9999元', trigger: 'blur' }
  ]
}

// 监听关键状态变化，自动保存到 SessionStorage
watch([orders, searchText, dialogVisible, isEditMode, () => ({ ...formData })], () => {
  saveToStorage({
    orders: orders.value,
    searchText: searchText.value,
    dialogVisible: dialogVisible.value,
    isEditMode: isEditMode.value,
    formData: { ...formData }
  })
}, { deep: true })

// 操作函数
const handleAdd = () => {
  isEditMode.value = false
  resetForm()
  dialogVisible.value = true
}

const handleEdit = (row) => {
  isEditMode.value = true
  Object.assign(formData, { ...row })
  dialogVisible.value = true
}

const handleDelete = (orderId) => {
  ElMessageBox.confirm('确定要删除该订单吗？', '警告', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    orders.value = orders.value.filter(u => u.orderId !== orderId)
    ElMessage.success('删除成功')
  })
}

const submitForm = async () => {
  await formRef.value.validate()
  if (isEditMode.value) {
    const index = orders.value.findIndex(u => u.orderId === formData.orderId)
    orders.value.splice(index, 1, { ...formData })
  } else {
    if (orders.value.some(u => u.orderId === formData.orderId)) {
      return ElMessage.warning('订单编号已存在')
    }
    orders.value.push({ ...formData })
  }
  dialogVisible.value = false
  ElMessage.success(isEditMode.value ? '修改成功' : '新增成功')
}

const resetForm = () => {
  formData.orderId = ''
  formData.customer = ''
  formData.restaurant = ''
  formData.phone = ''
  formData.amount = 0
  formData.paymentStatus = 'unpaid'
  formData.deliveryStatus = 'pending'
  formData.address = ''
}

// 初始化时确保状态正确恢复
onMounted(() => {
  // 如果从存储中恢复了对话框状态，确保表单验证规则已正确应用
  if (dialogVisible.value && formRef.value) {
    formRef.value.clearValidate()
  }
})
</script>

<style scoped lang="scss">
.order-management {
  padding: 24px;
  background: #fff8f5;
  min-height: 100vh;

  .operation-bar {
    padding: 16px 24px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(231,76,60,0.08);
    margin-bottom: 24px;
    display: flex;
    align-items: center;
    gap: 16px;
  }

  :deep(.table-header) th {
    background-color: #fff8f5 !important;
    color: #e67e22;
    font-weight: 600;
    height: 56px;
  }

  .el-table {
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(231,76,60,0.08);
    
    .el-tag {
      font-size: 13px;
      padding: 0 8px;
      height: 26px;
      line-height: 24px;
    }
  }
}

.el-dialog {
  border-radius: 12px;
  
  .el-dialog__header {
    border-bottom: 1px solid #ffe0b2;
    margin: 0 24px;
    padding: 24px 0 16px;
  }
  
  .el-dialog__body {
    padding: 24px 32px;
  }
  
  .el-dialog__footer {
    border-top: 1px solid #ffe0b2;
    padding: 16px 24px;
  }
}

.el-form-item {
  margin-bottom: 20px;
}
</style>
